/**
 * @description 获取canvas 2D对象
 */
export const getCanvasCtx = (id) => {
	return new Promise(resolve => {
		wx.createSelectorQuery()
		.select(`#${id}`)
		.fields({ node: true, size: true })
		.exec(res => {
			// Canvas 对象
			const canvas = res[0].node;
			// Canvas 画布的实际绘制宽高
			const renderWidth = res[0].width;
			const renderHeight = res[0].height;
			// Canvas 绘制上下文
			const ctx = canvas.getContext('2d');

			// 初始化画布大小
			const dpr = wx.getWindowInfo().pixelRatio;
			canvas.width = renderWidth * dpr;
			canvas.height = renderHeight * dpr;
			ctx.scale(dpr, dpr);
			resolve({ ctx, canvas });
		});
	});
};

/**
 * base64图片转为binary格式图片
 */
export const base64ToBinary = (fileObj) => {
	return new Promise((resolve, reject) => {
		let filePath = `${wx.env.USER_DATA_PATH}/${fileObj.fileName}`;
		let base64 = fileObj.data.replace(/^data:image\/\w+;base64,/, "");
		wx.getFileSystemManager().writeFile({
			filePath: filePath,
			data: wx.base64ToArrayBuffer(base64),
			encoding: 'binary',
			success: () => {
				resolve(filePath);
			},
			fail: err => {
				reject('写入失败：', err);
			},
		});
	});
};

/**
 * @description 获取 可以drawImage的canvas图片对象
 */
export const getCanvasImageObj = async (url) => {
	const off = wx.createOffscreenCanvas({ type: '2d' });
	const image = off.createImage();
	await new Promise((resolve, reject) => {
		image.onload = resolve; // 绘制图片逻辑
		image.src = url;
	});
	return image;
};
